<template>
  <view class="member-center">
    <!-- 会员信息卡片 -->
    <view class="member-card">
      <view class="card-bg">
        <view class="member-info">
          <view class="member-level">
            <view class="level-icon">👑</view>
            <view class="level-text">{{ currentLevel.name }}</view>
          </view>
          <view class="member-benefits">
            <text>{{ currentLevel.description }}</text>
          </view>
        </view>

        <view class="progress-section">
          <view class="progress-info">
            <text>距离下一等级还需 {{ nextLevelPoints }} 积分</text>
          </view>
          <view class="progress-bar">
            <view class="progress-fill" :style="{ width: progressPercent + '%' }"></view>
          </view>
          <view class="progress-labels">
            <text>{{ currentLevel.minPoints }}</text>
            <text>{{ nextLevel ? nextLevel.minPoints : '满级' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 会员等级列表 -->
    <view class="levels-section">
      <view class="section-title">会员等级</view>
      <view class="levels-list">
        <view v-for="(level, index) in memberLevels" :key="index"
          :class="['level-item', { current: level.id === currentLevel.id }]">
          <view class="level-header">
            <view class="level-name">
              <view class="level-icon">{{ level.icon }}</view>
              <text>{{ level.name }}</text>
            </view>
            <view class="level-badge" v-if="level.id === currentLevel.id">当前</view>
          </view>

          <view class="level-requirements">
            <text>需要积分：{{ level.minPoints }}+</text>
          </view>

          <view class="level-benefits">
            <view class="benefit-title">专属权益：</view>
            <view class="benefits-list">
              <view v-for="(benefit, bIndex) in level.benefits" :key="bIndex" class="benefit-item">
                <text>• {{ benefit }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 积分获取指南 -->
    <view class="guide-section">
      <view class="section-title">积分获取指南</view>
      <view class="guide-list">
        <view class="guide-item" @click="navigateTo('/pages/ads/watch')">
          <view class="guide-icon">📺</view>
          <view class="guide-info">
            <view class="guide-title">观看广告</view>
            <view class="guide-desc">每次可获得0.5-1.5积分</view>
          </view>
          <view class="guide-arrow">></view>
        </view>

        <view class="guide-item" @click="navigateTo('/pages/invite/index')">
          <view class="guide-icon">👥</view>
          <view class="guide-info">
            <view class="guide-title">邀请好友</view>
            <view class="guide-desc">好友注册可获得5积分</view>
          </view>
          <view class="guide-arrow">></view>
        </view>

        <view class="guide-item">
          <view class="guide-icon">🎯</view>
          <view class="guide-info">
            <view class="guide-title">完成任务</view>
            <view class="guide-desc">每日任务奖励丰厚</view>
          </view>
          <view class="guide-arrow">></view>
        </view>

        <view class="guide-item">
          <view class="guide-icon">💰</view>
          <view class="guide-info">
            <view class="guide-title">充值奖励</view>
            <view class="guide-desc">充值即送额外积分</view>
          </view>
          <view class="guide-arrow">></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getMemberInfo, getMemberLevels } from '@/api/members.js'
import { getPointsBalance } from '@/api/points.js'

export default {
  name: 'MemberCenterPage',

  data() {
    return {
      currentLevel: {
        id: 1,
        name: '普通会员',
        icon: '🥉',
        minPoints: 0,
        description: '享受基础服务'
      },
      nextLevel: null,
      memberLevels: [
        {
          id: 1,
          name: '普通会员',
          icon: '🥉',
          minPoints: 0,
          benefits: ['基础打印服务', '积分兑换商品', '客服支持']
        },
        {
          id: 2,
          name: '银牌会员',
          icon: '🥈',
          minPoints: 100,
          benefits: ['打印9.5折优惠', '专属客服', '优先处理', '生日礼品']
        },
        {
          id: 3,
          name: '金牌会员',
          icon: '🥇',
          minPoints: 500,
          benefits: ['打印9折优惠', '免费加急服务', '专属活动', '月度礼品']
        },
        {
          id: 4,
          name: '钻石会员',
          icon: '💎',
          minPoints: 1000,
          benefits: ['打印8.5折优惠', '免费配送', 'VIP专线', '季度大礼包']
        },
        {
          id: 5,
          name: '至尊会员',
          icon: '👑',
          minPoints: 2000,
          benefits: ['打印8折优惠', '专属定制', '一对一服务', '年度豪礼']
        }
      ],
      userPoints: 0,
      nextLevelPoints: 0,
      progressPercent: 0
    }
  },

  onLoad() {
    this.initStatusBar()
    this.loadMemberData()
  },

  onShow() {
    this.loadMemberData()
  },

  methods: {
    /**
     * 初始化状态栏高度
     */
    initStatusBar() {
      const systemInfo = uni.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight || 0

      if (typeof document !== 'undefined' && document.documentElement) {
        document.documentElement.style.setProperty('--status-bar-height', statusBarHeight * 2 + 'rpx')
      }
    },

    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack()
    },

    /**
     * 加载会员数据
     */
    async loadMemberData() {
      try {
        // 获取用户积分
        const pointsResult = await getPointsBalance()
        if (pointsResult.success) {
          this.userPoints = pointsResult.data.availablePoints || 0
        }

        // 获取会员信息
        const memberResult = await getMemberInfo()
        if (memberResult.success) {
          this.currentLevel = memberResult.data.currentLevel
        }

        // 获取会员等级列表
        const levelsResult = await getMemberLevels()
        if (levelsResult.success) {
          this.memberLevels = levelsResult.data
        }

        // 计算升级进度
        this.calculateProgress()
      } catch (error) {
        console.error('加载会员数据失败:', error)
        // 使用默认数据
        this.calculateProgress()
      }
    },

    /**
     * 计算升级进度
     */
    calculateProgress() {
      // 找到下一个等级
      const currentIndex = this.memberLevels.findIndex(level => level.id === this.currentLevel.id)
      this.nextLevel = currentIndex < this.memberLevels.length - 1 ? this.memberLevels[currentIndex + 1] : null

      if (this.nextLevel) {
        // 计算还需要的积分
        this.nextLevelPoints = Math.max(0, this.nextLevel.minPoints - this.userPoints)

        // 计算进度百分比
        const currentLevelPoints = this.currentLevel.minPoints
        const nextLevelPoints = this.nextLevel.minPoints
        const earnedPoints = this.userPoints - currentLevelPoints
        const totalNeeded = nextLevelPoints - currentLevelPoints

        this.progressPercent = Math.min(100, Math.max(0, (earnedPoints / totalNeeded) * 100))
      } else {
        // 已经是最高等级
        this.nextLevelPoints = 0
        this.progressPercent = 100
      }
    },

    /**
     * 页面跳转
     */
    navigateTo(url) {
      if (!url) {
        this.showError('页面路径错误')
        return
      }

      uni.navigateTo({
        url,
        fail: (error) => {
          console.error('页面跳转失败:', error)
          this.showError('页面跳转失败')
        }
      })
    },

    /**
     * 显示错误提示
     */
    showError(message) {
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.member-center {
  min-height: 100vh;
  background: #f5f5f5;
}

// 导航栏样式
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 32rpx;
  padding-top: var(--status-bar-height);
  background: #667eea;
  position: relative;
  z-index: 100;
  box-sizing: border-box;
}

.nav-left {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    opacity: 0.7;
    transform: scale(0.95);
  }
}

.back-icon {
  font-size: 36rpx;
  color: white;
  font-weight: bold;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: white;
}

.nav-right {
  width: 80rpx;
  height: 60rpx;
}

// 会员卡片
.member-card {
  margin: 20rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
}

.card-bg {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
  color: white;
}

.member-info {
  margin-bottom: 40rpx;
}

.member-level {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.level-icon {
  font-size: 48rpx;
  margin-right: 16rpx;
}

.level-text {
  font-size: 40rpx;
  font-weight: bold;
}

.member-benefits {
  font-size: 26rpx;
  opacity: 0.9;
}

.progress-section {
  .progress-info {
    font-size: 26rpx;
    margin-bottom: 16rpx;
    opacity: 0.9;
  }

  .progress-bar {
    height: 8rpx;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 4rpx;
    overflow: hidden;
    margin-bottom: 12rpx;
  }

  .progress-fill {
    height: 100%;
    background: white;
    border-radius: 4rpx;
    transition: width 0.3s ease;
  }

  .progress-labels {
    display: flex;
    justify-content: space-between;
    font-size: 22rpx;
    opacity: 0.8;
  }
}

// 等级列表
.levels-section {
  margin: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.levels-list {
  .level-item {
    background: white;
    border-radius: 16rpx;
    padding: 32rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

    &.current {
      border: 2rpx solid #667eea;
      background: linear-gradient(135deg, #f8f9ff 0%, #e6f7ff 100%);
    }
  }

  .level-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
  }

  .level-name {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    font-weight: bold;
    color: #333;

    .level-icon {
      font-size: 32rpx;
      margin-right: 12rpx;
    }
  }

  .level-badge {
    background: #667eea;
    color: white;
    font-size: 22rpx;
    padding: 6rpx 16rpx;
    border-radius: 20rpx;
  }

  .level-requirements {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 16rpx;
  }

  .level-benefits {
    .benefit-title {
      font-size: 26rpx;
      color: #333;
      margin-bottom: 12rpx;
    }

    .benefits-list {
      .benefit-item {
        font-size: 24rpx;
        color: #666;
        line-height: 1.6;
        margin-bottom: 8rpx;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
}

// 积分指南
.guide-section {
  margin: 20rpx;
}

.guide-list {
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.guide-item {
  display: flex;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background: #f8f9fa;
  }
}

.guide-icon {
  font-size: 40rpx;
  margin-right: 24rpx;
}

.guide-info {
  flex: 1;
}

.guide-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.guide-desc {
  font-size: 24rpx;
  color: #666;
}

.guide-arrow {
  font-size: 24rpx;
  color: #999;
}
</style>